<template>
  <div class="main-container container-limited container-fluid page-holder">
    <div class="easy-container"></div>
    <el-form ref="form" class="bold-label" label-position="top" :model="form" :rules="rules">
      <el-form-item label="社区名" prop="title" ref="title">
        <el-input v-model.trim="form.title" autofocus />
      </el-form-item>
      <el-form-item label="社区描述">
        <el-input v-model.trim="form.desc" />
      </el-form-item>
      <el-form-item label="社区封面">
        <div class="flex">
          <el-avatar :size="90" :src="previewAvatar" shape="square" class="m-l-16"/>
          <div class="body-line-height m-l-16">
            <div class="flex">
              <UploadAvatar :preview-url.sync="form.avatar" v-on:avatar="setAvatar" />
              <el-button size="small" class="m-l-10" @click="setAvatar({})">重置</el-button>
            </div>
            <p class="info">仅支持 jpg, jpeg, png 格式的图片类型。<br>图片允许的最大大小为2MB。</p>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="指定社区拥有者">
        <el-input v-model.trim="form.ownerId" type="number">
          <el-button
            slot="append"
            icon="el-icon-refresh-left"
            @click="form.ownerId = curUser.id"
          >
            重置
          </el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="isLoading">创建社区</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import UploadAvatar from '@/components/shared/UploadAvatar';

export default {
  name: 'CommunitiesCreate', // 创建社区界面
  components: { UploadAvatar },
  data() {
    return {
      form: {
        title: '',
        desc: '',
        avatar: '',
        avatarKey: undefined, // 封面key
        ownerId: this.$store.state.currentUser.id,
      },
      rules: {
        title: [{ required: true, validator: this.$va.communityTitle, trigger: 'blur' }],
      },
      isLoading: false, // 正在创建
    };
  },
  computed: {
    ...mapState({ curUser: 'currentUser' }),
    previewAvatar() { return this.form.avatar || 'http://file.learnerhub.net/default_product_avatar.jpg'; },
  },
  methods: {
    // 创建社区
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.isLoading = true;
          this.$api.communities.create(this.form)
            .then((res) => {
              this.$message.success('创建成功');
              this.$router.push(`/${this.$rp.COMMUNITIES}/${res.data.id}`);
            })
            .catch(() => {})
            .then(() => { this.isLoading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
    // 接受上传组件返回的头像数据
    setAvatar(avatar) {
      this.form.avatar = avatar.url;
      this.form.avatarKey = avatar.key;
    },
  },
};
</script>

<style></style>
